<?php
include 'Base.class.php';
require_once('autoload.php');

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;


/* 判断类型 */
switch ($_GET['action']) {
    /* 列出文件 */
    case 'listfile':
        $allowFiles = $CONFIG['fileManagerAllowFiles'];
        $listSize = $CONFIG['fileManagerListSize'];
        break;
    /* 列出图片 */
    case 'listimage':
    default:
        $allowFiles = $CONFIG['imageManagerAllowFiles'];
        $listSize = $CONFIG['imageManagerListSize'];
}

$allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

/* 获取参数 */
$size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
$start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
$end = $start + $size;

//获取七牛云配置
$base = new Base();
$qnConfig = $base->getQiniuConfig();

$accessKey = $qnConfig['access_key'];
$secretKey = $qnConfig['secret_key'];
$bucket = $qnConfig['bucket'];


$auth = new Auth($accessKey, $secretKey);
$bucketMgr = new BucketManager($auth);

// 要列取文件的公共前缀
$prefix = "";
// 上次列举返回的位置标记，作为本次列举的起点信息。
$marker = '';
// 本次列举的条目数
$limit = 100;
$delimiter = '/';
// 列举文件
list($ret, $err) = $bucketMgr->listFiles($bucket, $prefix, $marker, $limit, $delimiter);
if ($err != null)
{
    return json_encode($err);
}

// 获取图片完整路径并重新生成$list
$list = [];
$len = count($ret['items']);
for ($i=0; $i<$len; $i++)
{
    $list[$i]['url'] = $qnConfig['host'].'/'.$ret['items'][$i]['key'];
    $list[$i]['key'] = $ret['items'][$i]['key'];
}

$result = json_encode(array(
    "state" => "SUCCESS",
    "list" => $list,
    "start" => $start,
    "total" => count($ret['items'])
));

return $result;